#include "friendmodel.h"
#include "sdk/public/steam/steam_api.h"
extern bool G_Steam_Backend_Initialized;

FriendModel::FriendModel(QObject *parent)
    : QAbstractListModel(parent)
{}

int FriendModel::rowCount(const QModelIndex &parent) const
{
    // For list models only the root node (an invalid parent) should return the list's size. For all
    // other (valid) parents, rowCount() should return 0 so that it does not become a tree model.
    return filtered_friends.length();
}

QVariant FriendModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid())
        return QVariant();

    switch(role) {
    case NameRole:
        return QVariant(filtered_friends[index.row()].f_name);
    case StateRole:
        return QVariant(filtered_friends[index.row()].f_state);
    case SIDRole:
        return QVariant(QString("%1").arg(filtered_friends[index.row()].f_sid));
    default:
        return QVariant();
    }
}

QHash<int, QByteArray> FriendModel::roleNames() const {
    QHash<int, QByteArray> roles;
    roles[NameRole] = "name";
    roles[StateRole] = "state";
    roles[SIDRole] = "sid";
    return roles;
}

void FriendModel::reset() {
    qDebug() << "FriendMode::reset";
    emit beginResetModel();
    friends.clear();
    filtered_friends.clear();
    filter.clear();
    int count = SteamFriends()->GetFriendCount(k_EFriendFlagImmediate);
    qDebug() << "Steam friends count " << count;
    for (int i = 0; i < count; i++) {
        CSteamID friendSteamID = SteamFriends()->GetFriendByIndex(i, k_EFriendFlagImmediate );
        const char *friendName = SteamFriends()->GetFriendPersonaName( friendSteamID );
        EPersonaState state = SteamFriends()->GetFriendPersonaState(friendSteamID);
        Friend f;
        f.setName(QString(friendName));
        f.setSid(friendSteamID.ConvertToUint64());
        f.setState(state == k_EPersonaStateOnline ? 1 : 0);
        friends.append(f);
    }
    std::sort(friends.begin(), friends.end());
    filtered_friends = friends;
    emit endResetModel();
}

void FriendModel::FilterByName(QString filter) {
    emit beginResetModel();
    filtered_friends.clear();
    filter = filter;
    for (int i = 0; i < friends.size(); i++) {
        if (friends[i].f_name.contains(filter)) {
            filtered_friends.append(friends[i]);
        }
    }
    emit endResetModel();
}

void FriendModel::ClearFilter() {
    emit beginResetModel();
    filtered_friends.clear();
    filter.clear();
    filtered_friends = friends;
    emit endResetModel();

}
